# coding:utf-8
import json
from datetime import date, datetime, timedelta
import time
import threading
import psycopg2
import API_1

json_file = [r"../json/path_time.json","../json/hispath_time.json"]

# 配置文件
config = API_1.global_config
conn = psycopg2.connect(database=config['db_database'], user=config['db_user'],
                            password=config['db_password'], host=config['db_host'], port=config['db_port'])
cursor = conn.cursor()

# 初始时间
star_time = int(time.time())

# 获取日期 -----------------------------------------------
translate = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九',
             10: '十', 11: '十一', 12: '十二', 13: '十三', 14: '十四', 15: '十五'}
date = int(time.strftime("%d", time.localtime()))
if date > 30 :
    date = translate[1]
elif date > 15 :
    date = translate[date - 15]
else:
    date = translate[date]
date = date + "号"


# 根据坐标的时间信息更新数据库 工作函数 隔数秒执行一次
def work0():
    work('0')
def work1():
    work('1')
def work2():
    work('2')
def work(key):

    global star_time

    def _time(step):
        if step > 330:
            return _time(step-330)
        else:
            # 当前时间
            return step
    step =  _time(int(time.time()) - star_time)

    # 循环路径
    print(step)

    # 取当前时间之前second秒的点
    second = 10
    start_num = (step - second )  #  0  10  20
    stop_num = (step)             #  10   20  30
    with open(json_file[0],'r',encoding="utf-8") as json_f:
        path = json.load(json_f)
        lines = []
        hislines = []
        # print(path[key])
        for xy in path[key]:
            if xy[2] <= stop_num:
                hislines.append(xy[0:2])
                if xy[2] >= start_num:
                    # 收集时间段内的点
                    lines.append(xy[0:2])
        if lines == []:
            # 若此时间段无点，取最近历史时间位置
            lines = [hislines[-1]]

        print(hislines)
        print(lines)

        sql = f''' UPDATE car SET path = '{lines}', {date} = '{hislines}' WHERE key = '{key}';'''

        cursor.execute(sql)
        conn.commit()
    time.sleep(0)
    conn.close

# 间隔一定时间执行更新函数
def runTask(day=0, hour=0, min=0, second=0):
  # Init time
  now = datetime.now()
  strnow = now.strftime('%Y-%m-%d %H:%M:%S')
  print ("now:",strnow)
  # First next run time
  period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
  next_time = now + period
  strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
  time.sleep(0)
  while True:
      # Get system current time
      iter_now = datetime.now()
      iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
      if str(iter_now_time) == str(strnext_time):
          # Get every start work time
          print ("start work: %s" % iter_now_time)
          # Call task func

# -------------------------------执行程序：多线程-----------------------------------------------------------
          threads = [threading.Thread(target=work0()), threading.Thread(target=work1()), threading.Thread(target=work2())]
          for t in threads:
              t.start()
# ------------------------------------------------------------------------------------------
          # Get next iteration time
          iter_time = iter_now + period
          strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
          # Continue next iteration
          continue
  conn.close()

if __name__ == "__main__":
    # threading.Thread(target=api()),
    runTask(day=0, hour=0, min=0,second=10)



